<?php

namespace app\service;

use EasyWeChat\Factory;
use EasyWeChat\MiniProgram\Application;

class WechatService
{
    /**
     * 微信小程序实例缓存
     * @var Application|null
     */
    private static $miniProgramInstance = null;

    /**
     * 获取微信小程序实例
     * @return Application
     * @throws \Exception
     */
    public static function miniProgram(): Application
    {
        if (self::$miniProgramInstance === null) {
            $config = config('wechat.mini_program');
            
            if (empty($config['app_id']) || empty($config['secret'])) {
                throw new \Exception('微信小程序配置不完整，请检查 app_id 和 secret');
            }
            
            // 确保日志目录存在
            if (isset($config['log']['file'])) {
                $logDir = dirname($config['log']['file']);
                if (!is_dir($logDir)) {
                    mkdir($logDir, 0755, true);
                }
            }
            
            self::$miniProgramInstance = Factory::miniProgram($config);
        }
        
        return self::$miniProgramInstance;
    }

    /**
     * 获取微信公众平台实例
     * @return \EasyWeChat\OfficialAccount\Application
     * @throws \Exception
     */
    public static function officialAccount()
    {
        static $instance = null;
        
        if ($instance === null) {
            $config = config('wechat.official_account');
            
            if (empty($config['app_id']) || empty($config['secret'])) {
                throw new \Exception('微信公众平台配置不完整，请检查 app_id 和 secret');
            }
            
            // 确保日志目录存在
            if (isset($config['log']['file'])) {
                $logDir = dirname($config['log']['file']);
                if (!is_dir($logDir)) {
                    mkdir($logDir, 0755, true);
                }
            }
            
            $instance = Factory::officialAccount($config);
        }
        
        return $instance;
    }

    /**
     * 清除实例缓存（主要用于测试或重新加载配置）
     */
    public static function clearInstance(): void
    {
        self::$miniProgramInstance = null;
    }
}

